"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 视图
Case Name   : 视图指定definer时，备份恢复成功
Create At   : 2023.05.06
Owner       : @li-xin12345
Description :
    1、创建b库
    2、创建两个用户
    3、创建基表
    4、用户A赋权
    5、创建视图指定definer为步骤2用户
    6、用户B赋权
    7、导出
    8、导入
    9、数据一致
    10、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
    4、成功
    5、成功
    6、成功
    7、成功
    8、成功
    9、成功
    10、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class ViewTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.constant = Constant()
        self.passwd = macro.COMMON_PASSWD
        self.user1 = 'u_view_0002_01'
        self.user2 = 'u_view_0002_02'
        self.view_name = 'v_view_0002'
        self.tb_name = 't_view_0002'
        self.db_name_list = ['db_view_0002_01', 'db_view_0002_02',
                            'db_view_0002_03']

    def test_view(self):
        text = '-----step1:创建兼容b库数据库;expect:成功-----'
        self.log.info(text)
        for db_name in self.db_name_list:
            sql_cmd = f"drop database if exists {db_name};" \
                      f"create database {db_name} dbcompatibility ='B'" \
                      f" encoding ='UTF8';"
            self.log.info(sql_cmd)
            sql_res = self.sh_primary.execut_db_sql(sql_cmd, dbname='postgres')
            self.log.info(sql_res)
            self.assertIn(self.constant.DROP_DATABASE_SUCCESS, sql_res,
                          text + f'删除{db_name} 失败')
            self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                          text + f'创建{db_name} 失败')

        text = '-----b库下查询dolphin插件-----'
        self.log.info(text)
        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        for db_name in self.db_name_list:
            res = self.sh_primary.execut_db_sql(sql_cmd, dbname=db_name)
            self.log.info(res)
            self.assertIn('extname', res, '查询失败')
            self.assertIn('dolphin', res, '执行失败' + text)

        text = '-----step2:创建两个用户; expect:成功-----'
        self.log.info(text)
        sql_cmd = f"""drop user if exists {self.user1};
        drop user if exists {self.user2};
        create user {self.user1} password '{macro.COMMON_PASSWD}';
        create user {self.user2} password '{macro.COMMON_PASSWD}';
        """
        self.log.info(sql_cmd)
        res = self.sh_primary.execut_db_sql(sql_cmd)
        self.assertEqual(res.count(self.constant.DROP_ROLE_SUCCESS_MSG), 2,
                         '执行失败' + text)
        self.assertEqual(res.count(self.constant.CREATE_ROLE_SUCCESS_MSG), 2,
                         '执行失败' + text)

        text = '-----step3:创建基表; expect:成功-----'
        self.log.info(text)
        sql_cmd = f'drop table if exists {self.tb_name} cascade;' \
                  f'create table {self.tb_name}(c1 int, c2 varchar(20));'
        self.log.info(sql_cmd)
        res = self.sh_primary.execut_db_sql(sql_cmd,
                                            dbname=self.db_name_list[0])
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, '删表失败')
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, res, '建表失败')

        text = '-----step4:用户A赋权; expect:成功-----'
        self.log.info(text)
        sql = f'grant all on schema public to {self.user1};' \
              f'grant select,insert,delete,update on {self.tb_name}' \
              f' to {self.user1};'
        self.log.info(sql)
        res = self.sh_primary.execut_db_sql(sql,
                                            dbname=self.db_name_list[0])
        self.assertEqual(res.count(self.constant.GRANT_SUCCESS_MSG), 2)

        text = '-----step5:创建视图指定definer为步骤2用户;expect:成功-----'
        self.log.info(text)
        sql = f'create definer={self.user1} view {self.view_name}' \
              f' as select * from {self.tb_name};'
        self.log.info(sql)
        res = self.sh_primary.execut_db_sql(sql,
                                            dbname=self.db_name_list[0])
        self.assertIn(self.constant.CREATE_VIEW_SUCCESS_MSG, res, '建视图失败')

        text = '-----step6:用户B赋权;expect:成功-----'
        self.log.info(text)
        sql = f'grant select,insert,delete,update on' \
              f' {self.view_name} to {self.user2}; '
        self.log.info(sql)
        res = self.sh_primary.execut_db_sql(sql, dbname=self.db_name_list[0])
        self.assertIn(self.constant.GRANT_SUCCESS_MSG, res, text)

        text = '-----step7:导出;expect:成功-----'
        self.log.info(text)
        port = self.user_node.db_port
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_dump {self.db_name_list[0]} -F c -f ' \
              f'$GAUSSHOME/{self.view_name}.dmp -p {port}'
        self.log.info(cmd)
        res = self.user_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn(self.constant.GS_DUMP_SUCCESS_MSG, res, text + '执行失败')

        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_dump {self.db_name_list[0]} -F p -f ' \
              f'$GAUSSHOME/{self.view_name}.sql -p {port}'
        res = self.user_node.sh(cmd).result()
        self.log.info(cmd)
        self.log.info(res)
        self.assertIn(self.constant.GS_DUMP_SUCCESS_MSG, res, text + '执行失败')

        text = '-----step8:导入;expect:成功-----'
        self.log.info(text)
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gs_restore -d {self.db_name_list[1]} ' \
              f'$GAUSSHOME/{self.view_name}.dmp -p {port}'
        self.log.info(cmd)
        res = self.user_node.sh(cmd).result()
        self.log.info(res)
        self.assertIn('successful', res, text + '执行失败')
        cmd = f'source {macro.DB_ENV_PATH};' \
              f'gsql -d {self.db_name_list[2]} -f ' \
              f'$GAUSSHOME/{self.view_name}.sql -p {port}'
        self.log.info(cmd)
        res = self.user_node.sh(cmd).result()
        self.log.info(res)
        self.assertNotIn('Error', res, text + '执行失败')

        text = '-----step9:数据一致;expect:成功-----'
        self.log.info(text)
        res_list = []
        for db_name in self.db_name_list:
            res = self.sh_primary.execut_db_sql(f'\d', dbname=db_name)
            self.log.info(res)
            self.assertEqual('4 rows', res.splitlines()[-1].replace("(", "")
                             .replace(")", ""), "执行失败" + text)
            self.log.info(res_list)
            res_list.append(res)
        self.log.info(res_list)
        self.assertEqual(res_list[0], res_list[1], text)
        self.assertEqual(res_list[0], res_list[2], text)

    def tearDown(self):
        text = '-----step10:清理环境; expect:成功-----'
        self.log.info(text)
        res_list = []
        for db_name in self.db_name_list:
            drop_db = f'drop database if exists {db_name};'
            self.log.info(drop_db)
            res = self.sh_primary.execut_db_sql(drop_db)
            self.log.info(res)
            res_list.append(res)
        self.log.info(res_list)
        drop_user = f'drop user if exists {self.user1};' \
                    f'drop user if exists {self.user2};'
        self.log.info(drop_user)
        drop_user_res = self.sh_primary.execut_db_sql(drop_user)
        self.assertIn(self.constant.DROP_ROLE_SUCCESS_MSG, drop_user_res, text)
        self.assertEqual(res_list.count(self.constant.DROP_DATABASE_SUCCESS),
                         3, text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
